package com.example.yupao_project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yupao_project.component.*;
import com.example.yupao_project.entity.Team;
import com.example.yupao_project.entity.User;
import com.example.yupao_project.entity.UserTeam;
import com.example.yupao_project.entity.infovo.TeamUserVo;
import com.example.yupao_project.entity.param.*;
import com.example.yupao_project.exception.BusinessException;
import com.example.yupao_project.service.TeamService;
import com.example.yupao_project.service.UserTeamService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: 杰
 * @date: 2024/5/13 14:19
 */
@RequestMapping("/team")
@RestController
@Slf4j
public class TeamController {
    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private SessionUtil sessionUtil;

    /**
     * 增加队伍
     *
     * @param team 队伍信息
     * @return ResultUtils
     */
    @PostMapping("/add")
    public BaseResponse<Long> add(@RequestBody TeamAdd team, HttpServletRequest request) throws Exception {
        if (team == null) throw new BusinessException(ErrorCode.NULL_ERROR);
        User loginUser = (User) sessionUtil.getSession(request);
        Team team1 = new Team();
        BeanUtils.copyProperties(team, team1);
        return ResultUtils.success(teamService.addTeam(team1, loginUser));
    }


    /**
     * 获取team
     *
     * @param id 队伍id
     * @return ResultUtils
     */
    @GetMapping("/get")
    public BaseResponse<Team> get(long id) {
        if (id <= 0) throw new BusinessException(ErrorCode.NULL_ERROR);
        Team team = teamService.getById(id);
        if (team == null) throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        return ResultUtils.success(team);
    }

    /**
     * 获取team list
     *
     * @param teamQuery team参数
     * @return ResultUtils
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVo>> getList(TeamQuery teamQuery, HttpServletRequest request) throws Exception {
        User loginUser = (User) sessionUtil.getSession(request);
        List<TeamUserVo> teamList = teamService.listTeams(teamQuery, loginUser);
        final List<Long> teamIdList = teamList.stream().map(TeamUserVo::getId).collect(Collectors.toList());
        //判断用户是否加入此队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception ignored) {}
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }

    /**
     * 分页查询队伍
     * @param teamQuery 查询信息
     * @return BaseResponse<Page<Team>>
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> getListToPage(TeamQuery teamQuery) {
        if (teamQuery == null) throw new BusinessException(ErrorCode.NULL_ERROR);
        Team team = new Team();
        BeanUtils.copyProperties(team, teamQuery);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> ret = teamService.page(page, queryWrapper);
        return ResultUtils.success(ret);
    }

    /**
     * 更新队伍信息
     *
     * @param teamUpdateRe 更新内容
     * @param request      request
     * @return BaseResponse<Boolean>
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRe teamUpdateRe, HttpServletRequest request) {
        if (teamUpdateRe == null) throw new BusinessException(ErrorCode.NULL_ERROR);
        User loginUser = (User) sessionUtil.getSession(request);
        if (loginUser == null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        boolean ret = teamService.updateTeam(teamUpdateRe, loginUser);
        return ResultUtils.success(ret);
    }

    /**
     * 加入队伍
     *
     * @param teamJoinRe 加入队伍的信息
     * @param request    request
     * @return BaseResponse<Boolean>
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRe teamJoinRe, HttpServletRequest request) {
        User user = (User) sessionUtil.getSession(request);
        if (user == null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        boolean ret = teamService.joinTeam(teamJoinRe, user);
        return ResultUtils.success(ret);
    }

    /**
     * 退出队伍
     * @param teamQuitRe 队伍信息
     * @param request request
     * @return BaseResponse<Boolean>
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quit(@RequestBody TeamQuitRe teamQuitRe, HttpServletRequest request) {
        User user = (User) sessionUtil.getSession(request);
        return ResultUtils.success(teamService.quit(teamQuitRe, user));
    }

    /**
     * 删除队伍
     * @param teamDeleteRe 队伍信息
     * @param request request
     * @return BaseResponse<Boolean>
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> delete(@RequestBody TeamDeleteRe teamDeleteRe,HttpServletRequest request) {
        User user = (User) sessionUtil.getSession(request);
        return ResultUtils.success(teamService.delete(teamDeleteRe.getId(), user));
    }


    /**
     * 查看我创建的队伍
     * @param teamQuery 查询信息
     * @param request 登录信息
     * @return BaseResponse<List<TeamUserVo>>
     * @throws Exception
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVo>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) throws Exception {
        if (teamQuery == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        User loginUser = (User) sessionUtil.getSession(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVo> teamUserVoList = teamService.listTeams(teamQuery,loginUser);
        return ResultUtils.success(teamUserVoList);
    }

    /**
     * 查询加入的队伍
     * @param teamQuery 队伍信息
     * @param request request
     * @return BaseResponse<List<TeamUserVo>>
     * @throws Exception
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVo>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) throws Exception {
        if (teamQuery == null) throw new BusinessException(ErrorCode.NULL_ERROR);
        User loginUser = (User) sessionUtil.getSession(request);
        if (loginUser == null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        ArrayList<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);
        List<TeamUserVo> teamList = teamService.listTeams(teamQuery,loginUser);
        for (TeamUserVo teamUserVo : teamList) {
            teamUserVo.setHasJoin(true);
        }
        return ResultUtils.success(teamList);
    }
}

